/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-16 10:57:09
 * @Description  : 日志接口的验证器
 */

const Joi = require('joi')
const R = require('@/models/Response')
const { ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const { IS_INTEGER, IS_UNSAFE_INTEGER } = require('@/constants/joiSchema')
const { LOG_TYPE } = require('@/constants/log')

const logSchema = {
  page: IS_INTEGER.min(1).default(1),
  pageSize: IS_INTEGER.min(1).default(999),
  type: Joi.string().valid(...Object.values(LOG_TYPE)),
  userIds: Joi.array().items(IS_UNSAFE_INTEGER),
  startTime: Joi.date(),
  endTime: Joi.date().when('startTime', {
    is: Joi.exist(),
    then: Joi.date().greater(Joi.ref('startTime')),
    otherwise: Joi.date().allow(null)
  })
}

/**
 * @description 日志列表查询的参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.listLogValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: logSchema.page,
    pageSize: logSchema.pageSize,
    type: logSchema.type,
    userId: IS_UNSAFE_INTEGER,
    startTime: logSchema.startTime,
    endTime: logSchema.endTime
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}

/**
 * @description 查询用户自己的日志参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.listUserLogValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: logSchema.page,
    pageSize: logSchema.pageSize,
    type: logSchema.type
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}

/**
 * @description 查询用户的登录设备参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.listLogDeviceValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: logSchema.page,
    pageSize: logSchema.pageSize
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}
